package com.example.networkprofiler;
import java.net.*;
import java.security.SecureRandom;
import java.io.*;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import android.net.TrafficStats;


public class SpeedTestThread implements Runnable {
	 SecureRandom sr;
	 ChannelSftp c;
	 OutputStream recvStream;
	 String fileName;
	 Session session;
	 static AtomicInteger count = null;
	 static long startTime = 0;
	 static long startData = 0;
	 static long endTime = 0;
	 static long endData = 0;
	
	public SpeedTestThread(String username,String passwd,int i){
		if(count == null) count = new AtomicInteger(1);
		else {			
			count.getAndAdd(1);
		}
		sr = new SecureRandom();
		recvStream = new ByteArrayOutputStream();
		fileName = "1mb.txt";
		JSch jsch = new JSch();
		try{
		session = jsch.getSession(username, "sslab02.cs.purdue.edu", 22);
		//System.out.println(System.getProperty("user.dir"));
					
		UserInfo ui = new MyUserInfo(passwd);
	      session.setUserInfo(ui);
	 
	      session.connect();
	 
	      Channel channel=session.openChannel("sftp");
	      channel.connect();
	      c=(ChannelSftp)channel;
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public void run(){
		try{
			startTiming();
			c.get(fileName,recvStream);
			endTiming();
			c.quit();
			session.disconnect();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public synchronized void startTiming(){
		if(count.getAndDecrement() ==1) {
			startData = TrafficStats.getTotalRxBytes();
			startTime=System.currentTimeMillis();
		}else{
			System.gc();
		}
	}
	
	public synchronized void endTiming(){
		if(count.getAndIncrement() ==0){			
			endTime = System.currentTimeMillis(); 
			endData = TrafficStats.getTotalRxBytes();
		}
	}
	
	public static void main(String args[]){
		Thread[] t = new Thread[4];
		for(int i = 0 ; i < 4 ; i++){
			t[i] = new Thread(new SpeedTestThread("jin72","mark1990",i));
		}
		for(int i = 0 ; i < 4 ; i++){
			t[i].start();
		}
		for(int i = 0 ; i < 4 ; i++){
			try{
			t[i].join();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		for(int i = 0 ; i < 4 ; i++){
			t[i].yield();
		}
		System.out.println(SpeedTestThread.startTime);
		System.out.println(SpeedTestThread.endTime);
		System.out.println(SpeedTestThread.endTime - SpeedTestThread.startTime );
 	}
}
